package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 设备Service业务层处理
 * 
 * @author qianyi
 * @date 2025-05-03
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private Client iotClient;
    @Autowired
    private AliIoTConfigProperties aliIotConfigProperties;

    /**
     * 从物联网平台同步产品列表到redis
     */
    @Override
    public void syncProductList() {
        //1.从iot平台中获取所有的产品
        QueryProductListRequest request = new QueryProductListRequest();
        request.setCurrentPage(1);
        request.setPageSize(200);
        request.setIotInstanceId(aliIotConfigProperties.getIotInstanceId());
        QueryProductListResponse response;
        try {
            response = iotClient.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("获取物联网平台产品列表失败");
        }
        //判断接口是否调通
        if (!response.getBody().success){
            throw new BaseException(response.getBody().getErrorMessage());
        }
        //2.存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr( response.getBody().getData().getList().getProductInfo()));
    }

    /**
     * 从redis中获取所有产品信息
     *
     * @return
     */
    @Override
    public List<ProductVo>  getAllProduct() {
        //1.从redis中获取数据
        String result = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        //2.判断缓存中是否存在数据，如果redis中不存在数据，返回空集合
        if(StringUtils.isEmpty(result)){
            return Collections.emptyList();
        }
        //3.如果redis中存在数据，转换list返回
        return JSONUtil.toList(result, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1.判断设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if(count>0){
            throw new BaseException("设备名称重复,请重新输入");
        }
        //2.在iot平台里面新增设备
        RegisterDeviceRequest registerDeviceRequest = new RegisterDeviceRequest();
        registerDeviceRequest.setProductKey(deviceDto.getProductKey());
        registerDeviceRequest.setDeviceName(deviceDto.getDeviceName());
        registerDeviceRequest.setNickname(deviceDto.getNickname());
        registerDeviceRequest.setIotInstanceId(aliIotConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try {
            response = iotClient.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
//            throw new RuntimeException("注册设备失败");
            throw new RuntimeException("注册设备失败：" + e.getMessage(), e);

        }

        //判断接口是否调通
        if (!response.getBody().success){
            throw new BaseException(response.getBody().getErrorMessage());
        }
        //3.属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //iotid 是物联网平台对于设备的唯一标识
        device.setIotId(response.getBody().getData().getIotId());
        //4.获取产品名称
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setProductKey(deviceDto.getProductKey());
        queryProductRequest.setIotInstanceId(aliIotConfigProperties.getIotInstanceId());
        QueryProductResponse queryProductResponse;
        try {
            queryProductResponse = iotClient.queryProduct(queryProductRequest);
        } catch (Exception e) {
            throw new RuntimeException("查询产品失败");
        }
        //判断接口是否调通
        if (!queryProductResponse.getBody().success){
            throw new BaseException(queryProductResponse.getBody().getErrorMessage());
        }
        //设置产品名称
        device.setProductName(queryProductResponse.getBody().getData().getProductName());
        //判断位置类型是否是0，是0，则设置物理位置类型为-1
        if(device.getLocationType().equals(0)){
            device.setPhysicalLocationType(-1);
        }
        try {
            //5.保存到数据库
            save(device);
        } catch (Exception e) {
            //保存失败，删除物联网中的设备数据
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setDeviceName(device.getDeviceName());
            deleteDeviceRequest.setIotInstanceId(aliIotConfigProperties.getIotInstanceId());
            deleteDeviceRequest.setIotId(device.getIotId());
            deleteDeviceRequest.setProductKey(device.getProductKey());

            try {
                iotClient.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new RuntimeException("删除物联网设备失败");
            }

            throw new RuntimeException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    /**
     * 查询设备详情
     *
     * @param deviceDto
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //查询iot平台的设备数据
        QueryDeviceDetailRequest queryDeviceDetailRequest = new QueryDeviceDetailRequest();
        queryDeviceDetailRequest.setIotId(deviceDto.getIotId());
        queryDeviceDetailRequest.setIotInstanceId(aliIotConfigProperties.getIotInstanceId());
        queryDeviceDetailRequest.setProductKey(deviceDto.getProductKey());
        QueryDeviceDetailResponse queryDeviceDetailResponse;
        try {
            queryDeviceDetailResponse = iotClient.queryDeviceDetail(queryDeviceDetailRequest);
        } catch (Exception e) {
            throw new RuntimeException("查询设备详情失败");
        }
        //判断接口是否调通
        if (!queryDeviceDetailResponse.getBody().success){
            throw new BaseException(queryDeviceDetailResponse.getBody().getErrorMessage());
        }
        //获取数据
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = queryDeviceDetailResponse.getBody().getData();
        //根据iotid查询数据库设备
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, data.getIotId()));
        //第一次拷贝，只包含了数据库里面的设备数据
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);
        //第二次拷贝，包含了数据库里面的设备数据，以及物联网平台返回的数据
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    /**
     * 查询设备物模型运行状态
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIotConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = iotClient.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new RuntimeException("查询设备物模型运行状态失败");
        }
        //判断接口是否调通
        if (!response.getBody().success){
            throw new BaseException(response.getBody().getErrorMessage());
        }
        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 查询指定产品的已发布物模型中的功能定义详情
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIotConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = iotClient.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new RuntimeException("查询指定产品的已发布物模型中的功能定义详情失败");
        }
        //判断接口是否调通
        if (!response.getBody().success){
            throw new BaseException(response.getBody().getErrorMessage());
        }
        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 批量修改设备备注名称
     *
     * @param device
     * @return
     */
    @Transactional
    @Override
    public int batchUpdateDeviceNickname(Device device) {
        //查询设备是否存在
        Device dbDevice = getById(device.getId());
        if (ObjectUtil.isEmpty(dbDevice)){
            throw new BaseException("设备不存在");
        }
        //先更新设备
        //如果是随身设备，物理位置设为-1
        if (dbDevice.getLocationType().equals(0)){
            device.setPhysicalLocationType(-1);
        }
        //更新数据库中的设备信息
        try {
            deviceMapper.updateDevice(device);
        } catch (Exception e) {
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
        //更新设备名称
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        //设置参数
        request.setIotInstanceId(aliIotConfigProperties.getIotInstanceId());
        //设置设备列表
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo>
                list = new ArrayList<>();
        //设备对象
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo
                info = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        //把前端的参数传入接口的对象中
        BeanUtil.copyProperties(device, info);
        //把对象添加到设备列表中
        list.add(info);
        //把设备列表添加到参数中
        request.setDeviceNicknameInfo(list);
        BatchUpdateDeviceNicknameResponse response;
        try {
            response = iotClient.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new BaseException("更新设备失败");
        }
        //判断接口是否调通
        if (!response.getBody().success){
            throw new BaseException(response.getBody().getErrorMessage());
        }

        return 1;
    }

    /**
     * 删除设备
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteDeviceById(DeleteDeviceRequest request) {
        remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, request.getIotId()));
        request.setIotInstanceId(aliIotConfigProperties.getIotInstanceId());
        DeleteDeviceResponse response ;
        try {
             response = iotClient.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("删除设备失败");
        }
        //判断接口是否调通
        if (!response.getBody().success){
            throw new BaseException(response.getBody().getErrorMessage());
        }
        return 1;
    }


    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {

        return save(device)?1:0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {

        return updateById(device)?1:0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id)?1:0;
    }
}
